package com.sai.system.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sai.common.system.vo.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    final static String FIELD_CREATE_BY = "createBy";
    final static String FIELD_CREATE_TIME = "createTime";
    final static String FIELD_UPDATE_BY = "updateBy";
    final static String FIELD_UPDATE_TIME = "updateTime";

    /**
     * 新增数据执行
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasSetter = metaObject.hasSetter(FIELD_CREATE_BY) && metaObject.hasSetter(FIELD_CREATE_TIME) && metaObject.hasSetter(FIELD_UPDATE_BY) && metaObject.hasSetter(FIELD_UPDATE_TIME);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (hasSetter && user != null) {
            this.setFieldValByName(FIELD_CREATE_BY, user.getUsername(), metaObject);
            this.setFieldValByName(FIELD_CREATE_TIME, new Date(), metaObject);
            this.setFieldValByName(FIELD_UPDATE_BY, user.getUsername(), metaObject);
            this.setFieldValByName(FIELD_UPDATE_TIME, new Date(), metaObject);
        }
    }

    /**
     * 更新数据执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        boolean hasSetter = metaObject.hasSetter(FIELD_UPDATE_BY) && metaObject.hasSetter(FIELD_UPDATE_TIME);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (hasSetter && user != null) {
            this.setFieldValByName(FIELD_UPDATE_BY, user.getUsername(), metaObject);
            this.setFieldValByName(FIELD_UPDATE_TIME, new Date(), metaObject);
        }
    }

}
